﻿// eslint-disable-next-line
import { Table, Input, Button, InputNumber, Popconfirm, Form, message,Icon } from 'antd';
import Highlighter from 'react-highlight-words';
import React from 'react';

const EditableContext = React.createContext();
const { Search } = Input;
const rowSelection = {
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
  },
  onSelect: (record, selected, selectedRows) => {
    console.log(record, selected, selectedRows);
  },
  onSelectAll: (selected, selectedRows, changeRows) => {
    console.log(selected, selectedRows, changeRows);
  },
};

class EditableCell extends React.Component {
  getInput = () => {
    if (this.props.inputType === 'number') {
      return <InputNumber />;
    }
    return <Input />;
  };

  renderCell = ({ getFieldDecorator }) => {
    const {
      editing,
      dataIndex,
      title,
      inputType,
      record,
      index,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item style={{ margin: 0 }}>
            {getFieldDecorator(dataIndex, {
              rules: [
                {
                  required: true,
                  message: `Please Input ${title}!`,
                },
              ],
              initialValue: record[dataIndex],
            })(this.getInput())}
          </Form.Item>
        ) : (
            children
          )}
      </td>
    );
  };

  render() {
    return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
  }
}

class EditableTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = { 
      data:[], 
      count:100,
      editingKey: '',
      searchText: '',
      searchedColumn: '',
      sortedInfo: null,
     
    };
    this.columns = [
      {
        title:'编号',
        dataIndex:'id',
        width:'15%',
        editable: true,
        sorter: (a, b) => a.id - b.id,
        ...this.getColumnSearchProps('id'),
      },
      {
        title: '姓名',
        dataIndex: 'name',
        width: '20%',
        editable: true,
        ...this.getColumnSearchProps('name'),
      },
      {
        title: '年龄',
        dataIndex: 'age',
        width: '10%',
        editable: true,
        // ...this.getColumnSearchProps('age'),
        sorter: (a, b) => a.age - b.age,
        // defaultSortOrder: 'descend',
      },
      {
        title:'性别',
        dataIndex:'sex',
        width:'15%',
        editable: true,
        ...this.getColumnSearchProps('sex'),
      },
      {
        title: '学号',
        dataIndex: 'studentNum',
        width: '20%',
        editable: true,
        sorter: (a, b) => a.studentNum - b.studentNum,
        ...this.getColumnSearchProps('studentNum'),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        render: (text, record) => {
          const { editingKey } = this.state;
          const editable = this.isEditing(record);
          return editable ? (
            <span>
              <EditableContext.Consumer>
                {form => (
                  <a
                    onClick={() => this.save(form, record.key)}
                    style={{ marginRight: 8 ,color:'green'}}
                  >
                    保存
                  </a>
                )}
              </EditableContext.Consumer>
              <Popconfirm title="确定取消吗？" onConfirm={() => this.cancel(record.key)}>{/* title="确定取消吗？" onConfirm={() => this.cancel(record.key)} */}
                <a style={{color:'orange'}}>取消</a>
              </Popconfirm>
            </span>
          ) : (
              <span>
                <a disabled={editingKey !== ''} onClick={() => this.edit(record.key)}>
                  编辑
            </a>
                &nbsp;&nbsp;&nbsp;
            <Popconfirm title="确定删除吗?" onConfirm={() => this.handleDelete(record.key)}>
                  <a style={{color:'red'}}>删除</a>
                </Popconfirm>
              </span>
            );
        },
      },
    ];
  }
// 页面渲染时请求数据
  componentDidMount(){
    fetch('http://rap2api.taobao.org/app/mock/239134/course_evaluation/student_info')
    .then((d) =>{
      return d.json()
    })
    .then((d) =>{
      console.log(d)
      console.log(d.body.data[0].id)
      console.log(d.body.data[0].key)
      this.setState({
        data:d.body.data,
      })
      localStorage.setItem('data',JSON.stringify(this.state.data))
    })
    

  }

  // 搜索方法
  getColumnSearchProps = dataIndex => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={node => {
            this.searchInput = node;
          }}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
        />
        <Button
          type="primary"
          onClick={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
          icon="search"
          size="small"
          style={{ width: 90, marginRight: 8 }}
        >
          搜索
        </Button>
        <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 90 }}>
          重置
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <Icon type="search" style={{ color: filtered ? '#1890ff' : undefined }} />
    ),
    onFilter: (value, record) =>
      record[dataIndex]
        .toString()
        .toLowerCase()
        .includes(value.toLowerCase()),
    onFilterDropdownVisibleChange: visible => {
      if (visible) {
        setTimeout(() => this.searchInput.select());
      }
    },
    render: text =>
      this.state.searchedColumn === dataIndex ? (
        <Highlighter
          highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
          searchWords={[this.state.searchText]}
          autoEscape
          textToHighlight={text.toString()}
        />
      ) : (
        text
      ),
  });
// 搜索
  handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm();
    this.setState({
      searchText: selectedKeys[0],
      searchedColumn: dataIndex,
    });
  };
// 搜索重置
  handleReset = clearFilters => {
    clearFilters();
    this.setState({ searchText: '' });
  };

  isEditing = record => record.key === this.state.editingKey;
// 取消
  cancel = () => {
    this.setState({ editingKey: '' });
  };
// 保存
  save(form, key) {
    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      const newData = [...this.state.data];
      const index = newData.findIndex(item => key === item.key);
      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, {
          ...item,
          ...row,
        });
        localStorage.setItem('data',JSON.stringify(newData))
        this.setState({ data:newData, editingKey: '' });
      } else {
        newData.push(row);
        localStorage.setItem('data',JSON.stringify(newData))
        this.setState({ data: newData, editingKey: '' });

      }
    });
  }
// 修改数据
  edit(key) {
    this.setState({ editingKey: key });
  }
  // 删除一条数据
  handleDelete(key) {
    const newData = [...this.state.data];
    var arr= []
    arr = newData.filter(item => item.key !== key)
    localStorage.setItem('data',JSON.stringify(arr))
    this.setState({ data: arr });
  };
  // 新增一条数据
  handleAdd = () => {
    message.success('添加成功');
    fetch('http://rap2api.taobao.org/app/mock/239134/course_evaluation/student_info')
    .then((d) =>{
      return d.json()
    })
    .then((d) =>{
      console.log(d)
      const {data} = this.state
      const newData = {
        key: data.length+1,
        id:data.length+1,
        name: '默认张三',
        age: '默认'+32,
        sex:'默认'+1,
        studentNum: '默认'+2000,
      };
      this.setState({
        data: [newData,...data],
        // count:count+1
        
      });  
      console.log(this.state.id)
      localStorage.setItem('data',JSON.stringify(this.state.data))
    })
  };
  // 渲染表头及以上
  render() {
    const components = {
      body: {
        cell: EditableCell,
      },
    };

    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          inputType: col.dataIndex === 'age' ? 'number' : 'text',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: this.isEditing(record),
        }),
      };
    });

    return (
      <EditableContext.Provider value={this.props.form}>
        <Button onClick={this.handleAdd} type="primary" style={{ marginBottom: 16, marginRight: 800 }}>
          添加
        </Button>
        <Table
          // onChange={onChange}
          rowKey={record => record.id}
          components={components}
          bordered
          dataSource={this.state.data}
          columns={columns}
          rowClassName="editable-row"
          pagination={{
            onChange: this.cancel,
          }}
          rowSelection={rowSelection}
        />
      </EditableContext.Provider>
    );
  }
}

const StudentInfo = Form.create()(EditableTable);

export default StudentInfo